package com.example.shixun2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class EmojiAdapter extends RecyclerView.Adapter<EmojiAdapter.EmojiViewHolder> {

    private final List<String> emojiList;
    private final OnEmojiClickListener listener;

    // 1. 定义一个点击回调接口
    public interface OnEmojiClickListener {
        void onEmojiClick(String emoji);
    }

    // 2. 构造函数，接收数据源和回调监听
    public EmojiAdapter(List<String> emojiList, OnEmojiClickListener listener) {
        this.emojiList = emojiList;
        this.listener = listener;
    }

    @NonNull
    @Override
    public EmojiViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.emoji_list_item, parent, false);
        return new EmojiViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull EmojiViewHolder holder, int position) {
        String emoji = emojiList.get(position);
        holder.tvEmoji.setText(emoji);

        // 3. 绑定点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onEmojiClick(emoji);
            }
        });
    }

    @Override
    public int getItemCount() {
        return emojiList.size();
    }

    // 4. ViewHolder
    public static class EmojiViewHolder extends RecyclerView.ViewHolder {
        TextView tvEmoji;

        public EmojiViewHolder(@NonNull View itemView) {
            super(itemView);
            tvEmoji = itemView.findViewById(R.id.tv_emoji);
        }
    }
}